<?php
session_start();

    if (is_null($_SESSION["g2ulogin"]) || $_SESSION["g2uName"]=="undefined"){
        include_once 'close.php';
    } else {
       
        if((!isset($_FILES["file"]) || $_FILES["file"]["size"]==0)&& $_REQUEST["wishlist"]==1){
            echo "Opps, parece que no adjuntaste una imagen. Intenta nuevamente.";
            exit();
        }
        
        $conImagen = false;
        $desc = trim($_REQUEST["comentario"]);
        $desc = strip_tags($desc);
        //Para wishlist agrega foto obligatoriamente
        //Para post, depende, si hay imagen con peso agrega caso contrario no agrega.
        if($_REQUEST["wishlist"]==1 || (isset($_FILES["file"]) && $_FILES["file"]["size"]>=0)){

            include_once 'recursos/config.php';
            $allowedExts = array("gif", "jpeg", "jpg", "png","GIF", "JPEG", "JPG", "PNG");
            $temp = explode(".", $_FILES["file"]["name"]);
            $extension = end($temp);
            $type = $_FILES["file"]["type"];

            if ((($type == "image/gif") 
                    || ($type == "image/jpeg")
                    || ($type == "image/jpg")
                    || ($type == "image/pjpeg")
                    || ($type == "image/x-png")
                    || ($type == "image/png")) 
                && ($_FILES["file"]["size"] < 2572864) 
                && in_array($extension, $allowedExts)){

                $conImagen = true;
                if ($_FILES["file"]["error"] > 0){
                    echo "Oops! Ocurri&oacute; un error inesperado. Int&eacute;ntalo en unos minutos.";
                    //set trigger to inform admin;
                    exit();
                }else{
                    include_once 'recursos/config.php';
                    include_once 'recursos/funciones.php';
                    include_once 'recursos/image.php';

                    $cnf = new configuracion();
                    $imagen = new image();
                    
                    $pathname = $cnf->getAlbumURL()."".$_SESSION["g2uId"];
                    $pathnamemini = $cnf->getAlbumMiniURL()."".$_SESSION["g2uId"];
                    
                    if (!is_dir("".$pathname."")){
                        mkdir($pathname);
                    }
                    
                    if (!is_dir("".$pathnamemini."")){
                        mkdir($pathnamemini);
                    }

                    $fullname = generarAleatorio()."_".generarAleatorio()."_".generarAleatorio().".".$extension;

                    //Mini size
                    $imagen->resize($_FILES["file"]["tmp_name"], $_FILES["file"]["type"], $pathnamemini."/".$fullname);
                    
                    //Full size 
                    move_uploaded_file($_FILES["file"]["tmp_name"], "".$pathname."/".$fullname);
                    
                    
                    $img_route = $pathname;
                    $img_mini = $pathnamemini;
                    $img_name = $fullname;
                    $img_ws = "";

                    if(guardarFoto($desc, $img_route, $img_mini, $img_name, $img_ws)){
                      $id_foto = obtenerIdFoto();
                    } else {
                      echo "Opps, ocurri&oacute; algo inesperado al guardar la foto.";
                      unlink($pathname."/".$fullname);
                      exit();
                    }

                }
            }
        } else {
            $id_foto = 0;
        }

        $lat = $_REQUEST["lat"];
        $long = $_REQUEST["long"];
        $acc = $_REQUEST["acc"];
        
        $eid = $_REQUEST["evento"];

        if(guardarPost($desc, $id_foto, $lat, $long, $acc, $eid)){
            if($_REQUEST["wishlist"]==1){
                $id_post = obtenerIdPost();
                if(guardarWishlist($id_foto, $id_post)){
                    if(actualizarPost($id_post, obtenerIdWishlist())){
                        if($conImagen){
                            echo "Wishlist enviado!";
                        }else{
                            echo "Post enviado!";
                        }
                    } else {
                        echo "Opps, ocurri&oacute; algo inesperado al vincular el post con el wishlist.";
                    }
                } else {
                    echo "Opps, ocurri&oacute; algo inesperado al guardar el wishlist.";
                }
            } else {
                echo "Post enviado!";
            }
        } else {
            echo "Opps, ocurri&oacute; algo inesperado al guardar el post.";
        }
      ?>
<link type="text/css" href="css/g2u.css" rel="stylesheet"  media="screen" />
<script>
    parent.transition();
    parent.loadWishList();
</script>
      <?
    }

    function guardarFoto($desc, $img_route, $img_mini, $img_name, $img_ws){
        
        include_once 'bd_conn_class/conexionMysql.php';
        
        $bd = new conexionMysql();
        $sql = " INSERT INTO `photo` ( "
                    ." `ph_id`, `ph_u_id`, `ph_desc`, `ph_img_route`, "
                    ." `ph_img_mini_route`, `ph_img_name`, `ph_img_ws`, `ph_date` ) "
                ." VALUES ( "
                    ." NULL, '".$_SESSION["g2uId"]."', '".$desc."', '".$img_route."', "
                    ." '".$img_mini."', '".$img_name."', '".$img_ws."', NOW() ) ";

        $bd->ConectarBD();
        $rs = $bd->EjecutarQuery($sql);
        $bd->DesconectarBD();
        
        return $rs;
    }
    
    function obtenerIdFoto(){
        
        include_once 'bd_conn_class/conexionMysql.php';
        
        $bd = new conexionMysql();
        
        $sql = " SELECT MAX(ph_id) as maximo FROM `photo` WHERE `ph_u_id` = '".$_SESSION["g2uId"]."' ";

        $bd->ConectarBD();
        $rs = $bd->ObtenerDataEnRecurso($sql);
        
        while ($fila = mysql_fetch_array($rs)){
            $idFoto = $fila["maximo"];
        }
        
        $bd->DesconectarBD();
        
        return $idFoto;
    }
    
    function guardarPost($desc, $id_photo, $lat, $long, $acc, $eid=0){
        include_once 'bd_conn_class/conexionMysql.php';
        
        $bd = new conexionMysql();
        
        $sql = "INSERT INTO `post` ( "
                    ." `p_id`, `p_u_id`, `p_date`, `p_desc`, "
                    ." `p_ph_id`,`p_e_id`, "
                    ." `p_loc_lat`, `p_loc_long`, `p_loc_acc`) "
                ." VALUES ( "
                    ." NULL, '".$_SESSION["g2uId"]."', NOW(), '".$desc."', "
                    ." '".$id_photo."', '".$eid."', "
                    ." '".$lat."', '".$long."', '".$acc."' )";
        
        $bd->ConectarBD();
        $rs = $bd->EjecutarQuery($sql);
        $bd->DesconectarBD();
        
        return $rs;
    }
    
    function obtenerIdPost(){
        
        include_once 'bd_conn_class/conexionMysql.php';
        
        $bd = new conexionMysql();
        
        $sql = " SELECT MAX(p_id) as maximo FROM `post` WHERE `p_u_id` = '".$_SESSION["g2uId"]."' ";

        $bd->ConectarBD();
        $rs = $bd->ObtenerDataEnRecurso($sql);
        
        while ($fila = mysql_fetch_array($rs)){
            $idPost = $fila["maximo"];
        }
        
        $bd->DesconectarBD();
        
        return $idPost;
    }
    
    function guardarWishlist($id_foto, $id_post){
        include_once 'bd_conn_class/conexionMysql.php';
        
        $bd = new conexionMysql();
        
        $sql = " INSERT INTO `wishlist` ( "
                    ." `wl_id`, `wl_ph_id`, "
                    ." `wl_p_id`, `wl_u_id`, "
                    ." `wl_date`) "
                ." VALUES ( "
                    ." NULL, '".$id_foto."', "
                    ." '".$id_post."', '".$_SESSION["g2uId"]."', "
                    ." NOW()) ";
        
        $bd->ConectarBD();
        $rs = $bd->EjecutarQuery($sql);
        $bd->DesconectarBD();
        
        return $rs;
    }
    
    function obtenerIdWishlist(){
        
        include_once 'bd_conn_class/conexionMysql.php';
        
        $bd = new conexionMysql();
        
        $sql = " SELECT MAX(wl_id) as maximo FROM `wishlist` WHERE `wl_u_id` = '".$_SESSION["g2uId"]."' ";

        $bd->ConectarBD();
        $rs = $bd->ObtenerDataEnRecurso($sql);
        
        while ($fila = mysql_fetch_array($rs)){
            $idWishlist = $fila["maximo"];
        }
        
        $bd->DesconectarBD();
        
        return $idWishlist;
    }
    
    function actualizarPost($id_post, $id_wishlist){
        include_once 'bd_conn_class/conexionMysql.php';
        
        $bd = new conexionMysql();
        
        $sql = " UPDATE post set p_wl_id = '".$id_wishlist."' where p_id = '".$id_post."' ";
        
        $bd->ConectarBD();
        $rs = $bd->EjecutarQuery($sql);
        $bd->DesconectarBD();
        
        return $rs;
    }
    
 ?> 